import express from "express";
import { User, UserDetail, Borrowing } from "../models/model.js";
import { addUser, getUsers } from "../handlers/usersHandler.js";

const router = express.Router();

// 创建用户
router.post("/", async (req, res, next) => {
  try {
    const user = await addUser(req.body);
    res.status(201).json(user);
  } catch (err) {
    next(err);
  }
});

// 获取所有用户
router.get("/", async (req, res, next) => {
  try {
    const users = await getUsers();
    res.json(users);
  } catch (err) {
    next(err);
  }
});

// 获取用户详情
router.get("/:id", async (req, res, next) => {
  try {
    const user = await User.findByPk(req.params.id, {
      include: [{ model: UserDetail, as: "details" }],
    });

    if (user) {
      res.json(user);
    } else {
      res.status(404).json({ error: "User not found" });
    }
  } catch (err) {
    next(err);
  }
});

// 更新用户
router.put("/:id", async (req, res, next) => {
  try {
    const [updated] = await User.update(req.body, {
      where: { id: req.params.id },
    });

    if (updated) {
      const user = await User.findByPk(req.params.id);
      res.json(user);
    } else {
      res.status(404).json({ error: "User not found" });
    }
  } catch (err) {
    next(err);
  }
});

// 删除用户
router.delete("/:id", async (req, res, next) => {
  try {
    const deleted = await User.destroy({
      where: { id: req.params.id },
    });

    if (deleted) {
      res.status(204).end();
    } else {
      res.status(404).json({ error: "User not found" });
    }
  } catch (err) {
    next(err);
  }
});

// 获取用户借阅记录
router.get("/:id/borrowings", async (req, res, next) => {
  try {
    const borrowings = await Borrowing.findAll({
      where: { userId: req.params.id },
      include: [
        {
          model: BookInfo,
          as: "book",
        },
      ],
    });
    res.json(borrowings);
  } catch (err) {
    next(err);
  }
});

export default router;
